// pages/shoppingBag/shoppingBag.js
const app = getApp()
Page({
 data: {
  // 商品总数量
  ShoppingProductsNum: 0,
  productsList: [],
  checked: false,
  // 总价格
  price: 0
 },

 /**
  * 生命周期函数--监听页面加载
  */
 onLoad(options) {
 },
 // 复选框事件
 onChecked(event) {
  let num = this.data.productsList.filter(item => item.isShow === true)
  let res = this.forShopping(event.target.dataset.itemskucode)
  res.isShow = !res.isShow
  this.data.ShoppingProductsNum = num.length
  this.getShopping()
  this.totalCost()
 },
 // 数量增加
 addQty(event) {
  let res = this.forShopping(event.target.dataset.itemskucode)
  res.qty += 1
  this.getShopping()
  this.totalCost()
 },
 // 数量减少
 removeQty(event) {
  let res = this.forShopping(event.target.dataset.itemskucode)
  res.qty -= 1
  this.getShopping()
  this.totalCost()
 },
 // 获取最新的数据
 getShopping() {
  let res = this.data.productsList.filter(item => {
   return item.isShow === false
  }).reduce((a, b) => {
   return a + b.qty
  }, 0)
  this.setData({ productsList: app.globalData.shopping, ShoppingProductsNum: res })
 },
 // 遍历全局的购物车数据 返回查找到的那一条
 forShopping(itemskucode) {
  return app.globalData.shopping.find(item => item.itemSkuCode === itemskucode)
 },
 /**
  * 生命周期函数--监听页面显示
  */
 onShow() {
  this.getShopping()
 },
 // 全选
 onChange(event) {
  this.setData({ checked: event.detail })
  this.data.productsList.forEach((item, index, arr) => {
   item.isShow = !event.detail
  })
  this.getShopping()
  // 计算总价
  this.totalCost()

 },
 // 计算选中商品的总价
 totalCost() {
  let res = this.data.productsList.filter(item => {
   return item.isShow === false
  }).reduce((a, b) => {
   return a + (b.qty * b.price)
  }, 0)
  this.setData({ price: res })
 }
})